import axios from "axios";
import { Message, Notification } from "element-ui";
import qs from "qs";
import storage from "@/utils/storage";
import router from "@/router";
console.log(process.env.NODE_ENV);
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === "development"
      ? "https://iot.dideng.cc"
      : window.location.protocol + "//iot.dideng.cc",
  timeout: 5000,
});

const requestTimestamps = {};

service.interceptors.request.use(
  (config) => {
    // 如果请求包含参数，则将参数序列化后添加到请求标识符中 去重请求
    const currentTime = Date.now();
    config.headers["Content-Type"] = "application/json;charset=utf-8";
    config.headers["timestamp"] = currentTime;
    config.headers["g-sys"] = 1;
    config.headers["token"] =
      (storage.getStorage("dd_admin_user") &&
        storage.getStorage("dd_admin_user").token) ||
      null;
    config.headers["clientId"] =
      (storage.getStorage("dd_admin_user") &&
        storage.getStorage("dd_admin_user").user.userId) ||
      null;

    let requestIdentifier = config.url;
    if (config.params) {
      requestIdentifier += "?" + qs.stringify(config.params);
    } else if (
      config.data &&
      (config.method === "post" || config.method === "put")
    ) {
      requestIdentifier += "?" + qs.stringify(config.data);
    }
    if (
      requestTimestamps[requestIdentifier] &&
      currentTime - requestTimestamps[requestIdentifier] < 500 &&
      !config.repeat
    ) {
      return Promise.reject(new Error("请求过于频繁，请稍后再试"));
    } else {
      requestTimestamps[requestIdentifier] = currentTime;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.status === 0) {
      return res;
    } else if (res.status == 6001) {
      localStorage.clear();
      router.push("/login");
      Notification({
        title: "提示",
        message: res.msg || "Error",
        type: "error",
      });
    } else {
      Notification({
        title: "提示",
        message: res.msg || "Error",
        type: "error",
      });
      return Promise.reject(new Error(res.msg || "Error"));
    }
  },
  (error) => {
    console.log("err" + error);
    Notification({
      title: "提示",
      message: error.message || error.msg,
      type: "error",
    });

    return Promise.reject(error);
  }
);

export default service;
